import { registerMicroApps, start } from "qiankun";
import type { ObjectType, RegistrableApp, MicroAppStateActions } from "qiankun";

// 主应用和子应用通信的全局状态
let globalState: Record<string, any> = {};

// 全局状态变化监听器列表
const callbacks: Array<(state: Record<string, any>, prevState: Record<string, any>) => void> = [];

// 用于子应用获取和修改全局状态的API
export const actions: MicroAppStateActions = {
  setGlobalState(state: Record<string, any>) {
    try {
      console.log('设置全局状态前:', globalState);
      const prevState = { ...globalState };
      Object.assign(globalState, state);
      console.log('设置全局状态后:', globalState);
      
      // 通知所有监听器
      callbacks.forEach(callback => {
        try {
          callback(globalState, prevState);
        } catch (error) {
          console.error('调用全局状态变化回调失败:', error);
        }
      });
      
      return true;
    } catch (error) {
      console.error('设置全局状态失败:', error);
      return false;
    }
  },
  onGlobalStateChange(callback: (state: Record<string, any>, prevState: Record<string, any>) => void, fireImmediately?: boolean) {
    if (typeof callback === 'function') {
      // 移除已存在的相同回调
      const index = callbacks.indexOf(callback);
      if (index > -1) {
        callbacks.splice(index, 1);
      }
      
      // 添加新的回调
      callbacks.push(callback);
      console.log('添加全局状态变化监听器，当前监听器数量:', callbacks.length);
      
      // 如果需要立即触发
      if (fireImmediately) {
        try {
          console.log('立即触发全局状态变化回调');
          callback(globalState, {});
        } catch (error) {
          console.error('立即触发回调失败:', error);
        }
      }
    }
  },
  offGlobalStateChange(callback?: (state: Record<string, any>, prevState: Record<string, any>) => void) {
    try {
      if (callback) {
        // 移除特定回调
        const index = callbacks.indexOf(callback);
        if (index > -1) {
          callbacks.splice(index, 1);
          console.log('移除特定全局状态变化监听器，剩余监听器数量:', callbacks.length);
        }
      } else {
        // 清除所有回调
        callbacks.length = 0;
        console.log('清除所有全局状态变化监听器');
      }
      return true;
    } catch (error) {
      console.error('移除全局状态变化监听器失败:', error);
      return false;
    }
  }
};

// 初始化qiankun配置
async function initQiankun() {
  try {
    console.log('开始初始化qiankun...');
    
    // 动态导入Pinia相关模块
    console.log('正在动态导入Pinia相关模块...');
    const { useGlobalState } = await import('../stores/global');
    const { storeToRefs } = await import('pinia');
    
    // 获取全局状态
    console.log('获取Pinia store实例...');
    const globalStore = useGlobalState();
    const { userInfo } = storeToRefs(globalStore);
    
    console.log('获取到的用户信息:', userInfo.value);
    
    // 初始化全局状态
    console.log('初始化全局状态...');
    globalState = {
      userInfo: userInfo.value
    };
    
    console.log('全局状态初始化完成:', globalState);
    
    // 注册子应用
    console.log('开始注册子应用...');
    const appConfig: RegistrableApp<ObjectType>[] = [
      {
        name: "app1",
        entry: "http://localhost:5555/",
        container: "#micro-app-container",
        activeRule: "/app1",
        props: {
          actions,
          userInfo: userInfo.value
        }
      },
      {
        name: "app2",
        entry: "http://localhost:5556/",
        container: "#micro-app-container",
        activeRule: "/app2",
        props: {
          actions,
          userInfo: userInfo.value
        }
      },
      {
        name: "app3",
        entry: "http://localhost:5557/",
        container: "#micro-app-container",
        activeRule: "/app3",
        props: {
          actions,
          userInfo: userInfo.value
        }
      },
    ];
    
    registerMicroApps(appConfig);
    
    console.log('子应用注册完成');
    
    // 启动qiankun
    console.log('启动qiankun...');
    start({
      sandbox: {
        experimentalStyleIsolation: true,
      },
    });
    
    console.log('qiankun启动成功');
    
    // 测试全局状态设置，确保机制正常
    setTimeout(() => {
      console.log('测试：更新全局状态');
      actions.setGlobalState({ userInfo: userInfo.value });
    }, 1000);
  } catch (error) {
    console.error('初始化qiankun失败:', error);
  }
}

// 执行初始化
console.log('调用initQiankun函数进行初始化...');
void initQiankun();